﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WF = System.Windows.Forms;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace RCMC
{
	/// <summary>
	/// Interaction logic for Window1.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		private string mceHost = "localhost";
		private int mcePort = 10000;
		private bool allowExit = false;
		private WF.NotifyIcon notifyIcon;

		private TcpClient client;

		public MainWindow()
		{
			InitializeComponent();
#if DEBUG
#else
			notifyIcon = new WF.NotifyIcon();
			notifyIcon.Icon = Properties.Resources.notifyIcon;
			notifyIcon.Visible = true;
			notifyIcon.DoubleClick += delegate(object sender, EventArgs e) { this.Show(); };
			notifyIcon.ContextMenuStrip = new WF.ContextMenuStrip();
			//notifyIcon.ContextMenuStrip.Items.Add("Settings", null, delegate(object sender, EventArgs e)
			//{
			//  SettingsWindow w = new SettingsWindow();

			//  if (w.ShowDialog().GetValueOrDefault(false))
			//  {
			//    // apply new settings
			//  }
			//});
			//notifyIcon.ContextMenuStrip.Items.Add("-");
			notifyIcon.ContextMenuStrip.Items.Add("Exit", null, delegate(object sender, EventArgs e)
			{
				allowExit = true;
				if (client.Connected)
					client.Close();
				this.Close();
			});
#endif
		}

		private void Window_Loaded(object sender, RoutedEventArgs e)
		{
			this.Left = SystemParameters.FullPrimaryScreenWidth - this.Width - (SystemParameters.BorderWidth * 2);
			this.Top = SystemParameters.FullPrimaryScreenHeight - this.Height - (SystemParameters.BorderWidth * 2) + SystemParameters.CaptionHeight;

			if (!GlassWindow.ExtendedGlass(this))
			{
				this.Background = new ImageBrush(new BitmapImage(new Uri("pack://application:,,,/RCMC;component/Resources/wallpaper.jpg")));
			}

			string[] args = Environment.GetCommandLineArgs();
			if (args.Length >= 2)
				mceHost = args[1];
			if (args.Length >= 3)
				int.TryParse(args[2], out mcePort);

			hostName.Text = RCMC.Properties.Settings.Default["LastHostName"].ToString();
			gridControls.IsEnabled = false;
			disconnectButton.IsEnabled = false;
			client = new TcpClient();
		}

		private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
#if DEBUG
#else
			if (!allowExit)
			{
				e.Cancel = true;
				this.Hide();
			}
#endif
		}

		private void Window_Closed(object sender, EventArgs e)
		{
			notifyIcon.Visible = false;
			notifyIcon.Dispose();
		}

		private void Button_Click(object sender, RoutedEventArgs e)
		{
			Button b = (Button)sender;
			if (client.Connected)
			{
				SendMessage(b.CommandParameter.ToString());
			}
			else
			{
				disconnectButton_Click(null, null);
			}
		}

		private void SendMessage(string message)
		{
			byte[] buffer = System.Text.Encoding.UTF8.GetBytes(message + "\r\n");
			try
			{
				client.GetStream().Write(buffer, 0, buffer.Length);
			}
			catch (IOException)
			{
				client.Close();
			}
		}


		private void connectButton_Click(object sender, RoutedEventArgs e)
		{
			if (hostName.Text == "")
				return;

			string[] array = hostName.Text.Split(':');
			string host = array[0];
			int port = 10000;

			if (array.Length >= 2)
				int.TryParse(array[1], out port);

			hostName.IsEnabled = false;
			connectButton.IsEnabled = false;
			disconnectButton.IsEnabled = true;
			client.BeginConnect(host, port, new AsyncCallback(client_EndConnect), null);
		}

		private void disconnectButton_Click(object sender, RoutedEventArgs e)
		{
			client.Close();
			client = new TcpClient();

			gridControls.IsEnabled = false;
			hostName.IsEnabled = true;
			connectButton.IsEnabled = true;
			disconnectButton.IsEnabled = false;
		}

		private void client_EndConnect(IAsyncResult result)
		{
			try
			{
				if (!result.IsCompleted)
				{
					this.Dispatcher.Invoke((Action)(() =>
					{
						hostName.IsEnabled = true;
						connectButton.IsEnabled = true;
						disconnectButton.IsEnabled = false;
					}));

					return;
				}

				client.EndConnect(result);
				this.Dispatcher.Invoke((Action)(() =>
				{
					gridControls.IsEnabled = true;
					RCMC.Properties.Settings.Default["LastHostName"] = hostName.Text;
					RCMC.Properties.Settings.Default.Save();
				}));
			}
			catch (SocketException sex)
			{
				MessageBox.Show(sex.Message);
				this.Dispatcher.Invoke((Action)(() =>
				{
					hostName.IsEnabled = true;
					connectButton.IsEnabled = true;
					disconnectButton.IsEnabled = false;
				}));
			}
		}

		private void Window_KeyDown(object sender, KeyEventArgs e)
		{
			if (client.Connected)
			{
				switch (e.Key)
				{
					case Key.Enter:
						if (!disconnectButton.IsFocused)
						{
							SendMessage("button ok");
							e.Handled = true;
						}
						break;
					case Key.Back:
						SendMessage("button back");
						e.Handled = true;
						break;
					case Key.Apps:
						SendMessage("button info");
						e.Handled = true;
						break;
					case Key.Up:
						SendMessage("button up");
						e.Handled = true;
						break;
					case Key.Down:
						SendMessage("button down");
						e.Handled = true;
						break;
					case Key.Left:
						SendMessage("button left");
						e.Handled = true;
						break;
					case Key.Right:
						SendMessage("button right");
						e.Handled = true;
						break;

					case Key.PageUp:
						SendMessage("button channelup");
						e.Handled = true;
						break;
					case Key.PageDown:
						SendMessage("button channeldown");
						e.Handled = true;
						break;

					case Key.VolumeUp:
						SendMessage("volume up");
						e.Handled = true;
						break;
					case Key.VolumeDown:
						SendMessage("volume down");
						e.Handled = true;
						break;
					case Key.VolumeMute:
						SendMessage("volume switch");
						e.Handled = true;
						break;

					case Key.MediaPlayPause:
						SendMessage("button play");
						e.Handled = true;
						break;
					case Key.MediaStop:
						SendMessage("button stop");
						e.Handled = true;
						break;
					case Key.MediaNextTrack:
						SendMessage("button fwd");
						e.Handled = true;
						break;
					case Key.MediaPreviousTrack:
						SendMessage("button rew");
						e.Handled = true;
						break;
				}
			}
		}
	}
}
